<template>
  <div class="page-miH page-bgBack pb32">
    <div class="uplaodBoxs">
      <div class="spin-content pt24">
        <div class="ant-upload-select-text-box">
          <a-form class="forms" :form="form" :label-col="{ span: 9 }" :wrapper-col="{ span: 8 }">
            <a-form-item label="企业名称">
              <a-select
                :disabled="databatchDisabled"
                v-decorator="[
                  'companyId',
                  {
                    rules: [
                      {
                        required: true,
                        message: '企业名称不能为空'
                      }
                    ]
                  }
                ]"
                placeholder="请选择"
                @change="onSelect"
              >
                <a-select-option :value="item.id" v-for="item in companyIdArr" :key="item.id">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="税务分局">
              <a-select
                show-search
                :disabled="databatchDisabled"
                :filter-option="filterOption"
                v-decorator="[
                  'authId',
                  {
                    rules: [
                      {
                        required: true,
                        message: '税务分局不能为空'
                      }
                    ]
                  }
                ]"
                placeholder="请选择"
              >
                <a-select-option :value="item.id" v-for="item in authIdArr" :key="item.id">{{
                  item.responsibleAuthorityName
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="批次名称">
              <a-input
                :disabled="databatchDisabled"
                pstyle="width: 100%"
                placeholder="请输入"
                v-decorator="['batchName', { rules: [{ required: true, message: '批次名称不能为空' }] }]"
              />
            </a-form-item>
            <a-form-item label="税款所属月">
              <a-month-picker
                :disabled="databatchDisabled"
                style="width: 100%"
                valueFormat="YYYY-MM"
                placeholder="请选择"
                v-decorator="['period', { rules: [{ required: true, message: '税款所属月月不能为空' }] }]"
              />
            </a-form-item>
          </a-form>
          <a-form-item class="ml6" :wrapper-col="{ span: 24 }" style="text-align: center">
            <a-upload ref="upload" :showUploadList="false" :file-list="fileList" :before-upload="beforeUpload">
              <a-button :disabled="uploading" icon="plus" type="primary" style="width: 240px; margin-left: 12px">上传批次表</a-button>
              <!-- <a-button icon="plus" type="primary" style="width: 240px; margin-left: 12px" @click="$emit('upData', [])"> 测试 </a-button> -->
            </a-upload>
          </a-form-item>
        </div>
      </div>
      <div class="tipBox">
        <a-row style="color: #55565d; font-size: 16px; font-weight: 500; padding-bottom: 16px">导入说明</a-row>
        <a-row>
          <a-col :span="12">
            <div class="mb10">
              1、请使用模板上传
              <span @click="download('taxBatchDetail.xlsx')" class="add-primary">「算税数据上传模板」</span>
            </div>
            <div class="mb10">2、姓名、证件号码、本期收入为必填项，顺序可调整，但不可删除</div>
            <div class="mb10">2、不支持合并单元格上传</div>
          </a-col>
        </a-row>
      </div>
    </div>
  </div>
</template>
<script>
import { getToken } from "xqjr-module-auth";
import axios from "axios";
import qs from "qs";
import { getCompanyUnits } from "../api";
import { getCompanyAuthoritiesListAll } from "../../../api";

export default {
  data() {
    return {
      confirmLoading: false,
      form: this.$form.createForm(this, {}),
      companyIdArr: [],
      authIdArr: [],
      data: {},
      fileList: [],
      uploading: false,
      companyName: "",
      databatchDisable: false,
      databatch: null,
      databatchDisabled: false
    };
  },
  created() {
    this.onGetCompanyAuthoritiesListAll();
  },
  methods: {
    async onGetCompanyAuthoritiesListAll() {
      try {
        const { data } = await getCompanyAuthoritiesListAll({
          pageNo: 1,
          pageSize: 1000
        });
        this.companyIdArr = data;
        if (this.$route.query.databatch) {
          this.databatchDisabled = true;
          const databatch = JSON.parse(this.$route.query.databatch);
          this.databatch = databatch;
          this.onSelect(databatch.companyId);
          this.databatchDisable = true;
          this.$nextTick(() => {
            this.form.setFieldsValue({
              companyId: databatch.companyId,
              batchName: databatch.name,
              period: databatch.period
            });
            setTimeout(() => {
              this.form.setFieldsValue({
                authId: databatch.authId
              });
            }, 500);
          });
        } else {
          this.databatchDisable = false;
        }
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    onSelect(v) {
      this.companyIdArr.some((e) => {
        if (e.id === v) {
          this.companyName = e.name;
          this.authIdArr = e.companyAuthorityList;
          return true;
        }
      });
      setTimeout(() => {
        this.form.setFieldsValue({
          authId: undefined
        });
      });
    },
    beforeUpload(file) {
      if (this.fileList.length > 0) {
        this.$message.error("最多只能上传一个");
        return false;
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          this.fileList = [...this.fileList, file];
          if (this.fileList && this.fileList.length > 0) {
            const { fileList } = this;
            const formData = new FormData();
            fileList.forEach((file) => {
              console.log("file", file);
              formData.append("file", file);
            });
            formData.append("companyId", values.companyId);
            formData.append("companyName", this.companyName);
            formData.append("authId", values.authId);
            formData.append("batchName", values.batchName);
            formData.append("period", values.period.replace(/[-]/g, ""));
            formData.append("force", false);
            if (this.databatchDisable) {
              formData.append("batchId", this.databatchDisable ? this.databatch.id : "");
            }
            this.uploading = true;
            console.log("formData", formData);
            axios({
              url: `/tax/api/v1/calculateBatchDetails/importExcel`,
              method: "post",
              data: formData,
              headers: {
                token: getToken(),
                "Content-Type": "multipart/form-data"
              }
            })
              .then((res) => {
                console.log(res);
                if (res.data.code === 200) {
                  this.$message.success(res.data.msg);
                  this.uploading = false;
                  this.$router.replace({
                    name: "calculateImportTaxData",
                    query: {
                      successList: res.data.data.successList,
                      failList: res.data.data.failList,
                      fileName: fileList[0].name,
                      failExportUrl: res.data.data.failExportUrl,
                      batchId: res.data.data.batchId
                    }
                  });
                } else {
                  setTimeout(() => {
                    this.reset();
                  }, 1000);
                  this.$notification["error"]({
                    message: "error",
                    description: res.data.msg
                  });
                  this.uploading = false;
                }
              })
              .catch((err) => {
                console.log("err", err);
                setTimeout(() => {
                  this.reset();
                }, 1000);
                this.$notification["error"]({
                  message: "error",
                  description: err.msg
                });
                this.uploading = false;
              });
          } else {
            this.handleUploadError();
          }
        }
      });

      return false;
    },
    handleUploadError() {
      // this.$message.warning("没有文件");
      setTimeout(() => {
        this.reset();
      }, 1000);
    },
    handleSuccess(res) {
      var that = this;

      if (res.code === 200) {
        if (res.data) {
          this.$confirm({
            okText: "确定",
            title: `上传成功`,
            onOk() {
              if (res.data.failTransferAccountsDetailAddDTOList.length > 0) {
                // sessionStorage.setItem("paySalaryInfoId", res.data.transferAccountsBatchVO.id);
                that.$emit("upData", res.data.failTransferAccountsDetailAddDTOList);
              } else {
                that.$router.replace({ name: "applyForInfo", query: { id: "" } });
              }
            }
          });
        } else {
          this.$notification["error"]({
            message: "error",
            description: "上传失败"
          });
        }
      } else if (res.data === null) {
        this.$confirm({
          okText: "确定",
          title: res.msg,
          cancelButtonProps: false
        });
      } else {
        this.$notification["error"]({
          message: "error",
          description: res.msg || "上传失败"
        });
      }
      setTimeout(() => {
        this.reset();
      }, 1000);
    },
    download(templateName) {
      const token = this.$store.state.auth.token;
      let params = {};
      params = {
        templateName
      };

      axios({
        url: `/hr/api/v1/excel/template/download`,
        params,
        paramsSerializer: (param) => {
          return qs.stringify(param, { indices: false });
        },
        method: "GET",
        responseType: "blob",
        headers: {
          token: token
        }
      })
        .then((res) => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel"
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", "算税数据上传模板.xlsx");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch((err) => {
          console.log("error log --> ", err);
        });
    },
    reset() {
      this.fileList = [];
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    }
  }
};
</script>
<style lang="scss" scoped>
.tipBox {
  line-height: 18px;
  background: #faf9f9;
  border-radius: 4px;
  font-size: 12px;
  color: #595959;
  margin: 0 24px;
  width: calc(100% - 48px) !important;
  padding: 24px;
  border-radius: 4px;
}
.ant-upload-select-text-box {
  background: #fff;
  margin: 0 24px 24px 24px;
  // text-align: center;
  border-radius: 4px;
  padding: 60px 0;
  box-shadow: 0px 6px 16px 8px rgba(0, 0, 0, 0.03), 0px 4px 8px 0px rgba(0, 0, 0, 0.04);
  ::v-deep .ant-form-item-label > label {
    font-weight: normal !important;
    color: #55565d !important;
  }
  ::v-deep #remark {
    height: 80px !important;
  }
  .forms {
    width: 1000px;
    margin: 0 auto;
  }
}
.ant-upload-select-text-box ::v-deep .ant-upload-list {
  display: none;
}
.ant-upload-list-item-name {
  text-align-last: left;
}
.add-primary {
  color: var(--primary);
  cursor: pointer;
}
</style>
